package com.efounder.frame.activity;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.frame.baseui.EFActivity;
import com.efounder.frame.bean.FilterBean;
import com.efounder.frame.filter.FilterInterface;
import com.efounder.frame.fragment.FilterFragment;
import com.efounder.mobilemanager.R;
import com.efounder.util.EnvSupportManager;
import com.utilcode.util.ReflectUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;


/**
 * 通用的跳转Fragment Activity
 * 1.需要传入Fragment全名
 * 2.会把Activity的bundle传递到Fragment中
 *
 * @author hudq
 */

public class EFTransformFragmentActivity extends EFActivity implements FilterInterface {

    public static final String EXTRA_FRAGMENT_NAME = "fragmentName";
    /**
     * value:String
     **/
    public static final String EXTRA_TITLE_NAME = "titleName";
    /**
     * value:int(例如：View.VISIBLE)
     **/
    public static final String EXTRA_TITLE_LEFT_VISIBILITY = "left_visibility";
    /**
     * value:int(例如：View.VISIBLE)
     **/
    public static final String EXTRA_TITLE_RIGHT_VISIBILITY = "right_visibility";
    /**
     * value:boolean
     **/
    public static final String EXTRA_HIDE_TITLE_BAR = "hide_title_bar";

    private String fragmentName;
    private Fragment fragment;
    private FilterFragment filterFragment;
    private static final String TAG = "EFTransformFragmentActi";
    private List<StubObject> stubListByElementName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ef_activity_transform_fragment);
        initTitleView();
        fragmentName = getIntent().getStringExtra(EXTRA_FRAGMENT_NAME);

        try {
            fragment = (Fragment) Class.forName(fragmentName).newInstance();

            Log.e(TAG, "onCreate: " + fragmentName);
            fragment.setArguments(getIntent().getExtras());


            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.fragment_container, fragment);
            transaction.commit();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    @SuppressWarnings("WrongConstant")
    private void initTitleView() {
        //中-标题
        if (getIntent().hasExtra(EXTRA_TITLE_NAME)) {
            TextView titleTextView = (TextView) getEFTitleView().getCenterView();
            titleTextView.setText(getIntent().getStringExtra(EXTRA_TITLE_NAME));
        }
        //左-返回
        if (getIntent().hasExtra(EXTRA_TITLE_LEFT_VISIBILITY)) {
            int visibility = getIntent().getIntExtra(EXTRA_TITLE_LEFT_VISIBILITY, View.VISIBLE);
            getEFTitleView().getLeftImageView().setVisibility(visibility);
        }
        //右-菜单
        if (getIntent().hasExtra(EXTRA_TITLE_RIGHT_VISIBILITY)) {
            int visibility = getIntent().getIntExtra(EXTRA_TITLE_RIGHT_VISIBILITY, View.VISIBLE);
            getEFTitleView().getRightImageView().setVisibility(visibility);
        }
        //隐藏TitleBar
        //有的Fragment需要使用标题栏的按钮进行跳转，在此隐藏掉此Activity的标题栏
        if (getIntent().hasExtra(EXTRA_HIDE_TITLE_BAR) && getIntent().getBooleanExtra(EXTRA_HIDE_TITLE_BAR, true)) {
            getEFTitleView().setVisibility(View.GONE);
        } else {
            getEFTitleView().setVisibility(View.VISIBLE);
        }
        getEFTitleView().getFilterImageView().setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View v) {
                startFilter();
            }
        });
    }

    private void startFilter() {
        //todo 这是之前的消息过滤逻辑 暂时不用 2018/07/30
//        stubListByElementName = EFAppAccountRegistry.getStubListByElementName(EFXmlConstants.FILTER_MODULE);
//        if(stubListByElementName==null){
//            Toast.makeText(this, "资源配置文件不正确（127）", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        ArrayList<FilterNodeBean> filterNodeBeens = new ArrayList<>(stubListByElementName.size());
//
//        for (int i = 0; i < stubListByElementName.size(); i++) {
//            StubObject stubObject = stubListByElementName.get(i);
//            Hashtable stubTable = stubObject.getStubTable();
//            String title = (String) stubTable.get("title");
//            if (stubTable.containsKey("sql")) {
//
//                //没有子孩子,只有一级标题;
//                String sql = (String) stubTable.get("sql");
//                FilterNodeBean nodeBean = new FilterNodeBean(title);
//                nodeBean.setSql(sql);
//                filterNodeBeens.add(nodeBean);
//            } else {
//                //有二级标题
//
//                FilterNodeBean nodeBean = new FilterNodeBean(title);
//                filterNodeBeens.add(nodeBean);
//
//                String id = (String) stubTable.get("id");
//                List<StubObject> stub = EFAppAccountRegistry.getStubListByElementName(id);
//                if (stub == null) {
//                    Toast.makeText(this, "资源配置文件不正确", Toast.LENGTH_SHORT).show();
//                    return;
//                } else {
//
//                    for (int j = 0; j <stub.size(); j++) {
//                        StubObject childNode = stub.get(j);
//                        String  childSQL = (String) childNode.getStubTable().get("sql");
//                        String  childTitle = (String) childNode.getStubTable().get("title");
//                        String  textColor = (String) childNode.getStubTable().get("textColor");
//                        String  bgColor = (String) childNode.getStubTable().get("bgColor");
//
//                        FilterNodeBean childNodebean = new FilterNodeBean(childTitle);
//                        childNodebean.setSql(childSQL);
//                        childNodebean.setTextColor(textColor);
//                        childNodebean.setBgColor(bgColor);
//
//                        nodeBean.addChild(childNodebean);
//                    }
//                }
//
//            }
//
//
//        }
//       filterFragment = new FilterFragment(filterNodeBeens);
//        filterFragment.show(getSupportFragmentManager(),"ddd");
        //end  这是之前的消息过滤逻辑 暂时不用 2018/07/30

        if (EnvSupportManager.isSupportSearchMessage()) {
            try {
                int id = getIntent().getIntExtra("id", 1);
                ReflectUtils.reflect(getResources().getString(R.string.chat_filter_message_class))
                        .newInstance(id).method("show", getSupportFragmentManager(), "ddd");
            } catch (ReflectUtils.ReflectException e) {
                e.printStackTrace();
            }
        }
    }


    public void back(View view) {

        finish();
    }

    @Override
    // 设置回退
    // 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && fragment instanceof OnKeyBackListener) {
            OnKeyBackListener onKeyBackListener = (OnKeyBackListener) fragment;
            boolean forbidPropagate = onKeyBackListener.OnKeyBack(keyCode, event);
            if (forbidPropagate) {
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void beginFilter(String SQL) {

        if (TextUtils.isEmpty(SQL)) {
            return;
        }


        if (getResources().getString(R.string.PUBLIC_CHAT_FRAGMENT_PACKAGE_NAME).equals(fragmentName)) {
            FilterBean bean = new FilterBean();
            bean.content = SQL;
            bean.type = 1;
            EventBus.getDefault().post(bean);

            return;
        }

    }

    /**
     * 点击返回按钮的监听
     *
     * @author hudq
     */
    public interface OnKeyBackListener {
        /**
         * 点击返回
         *
         * @param keyCode KeyEvent.KEYCODE_BACK
         * @param event
         * @return 返回true, 防止事件进一步传播, 否则，表明你没有处理这个事件,它会继续传播。
         */
        public boolean OnKeyBack(int keyCode, KeyEvent event);
    }

}
